package com.qqtech.web.context;

import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import com.qqtech.core.common.constant.CoreConst;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.exception.BizzException;
import com.qqtech.core.common.exception.LoginException;
import com.qqtech.core.common.exception.OrderException;
import com.qqtech.core.common.exception.PayException;
import com.qqtech.core.common.util.JsonUtil;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.frame.controller.BaseControllerImpl;
import com.qqtech.core.frame.model.ABaseable;
import com.qqtech.core.frame.model.Result;
import com.qqtech.qquan.community.enums.CommunityConst;
import com.qqtech.qquan.user.enums.UserConst;
import com.qqtech.qquan.user.model.UserLoginVo;
import com.qqtech.qquan.user.service.UserLoginService;

public abstract class BaseWebController<T extends ABaseable, Q extends T> extends BaseControllerImpl<T, Q> {
	public static final Logger log = LoggerFactory.getLogger(BaseWebController.class);

	@Resource
	private UserLoginService userLoginService;

	/**
	 * 获取当前访问社区id
	 * 
	 * @return
	 */
	public Integer getCommunityVisitId() {
		HttpServletRequest request = getRequest();
		if (request != null) {
			String communityVisitId = request.getHeader(CommunityConst.MAPKEY_COMMUNITY_VISITID);
			if (StringUtil.isNotBlank(communityVisitId)) {
				return new Integer(communityVisitId);
			}
		}
		return 0;
	}

	/**
	 * 是否游客，true-是,false-否
	 * 
	 * @return
	 */
	public boolean isVisitor() {
		if (getLoginUser() == null) {
			return true;
		}
		return false;
	}

	/**
	 * 获取用户ID，如果未登陆，则返回空null
	 * 
	 * @return
	 */
	public Integer getUserId() {
		UserLoginVo vo = getLoginUser();
		if (vo != null && vo.getId() != null && vo.getId().intValue() != 0) {
			return vo.getId();
		}
		return null;
	}

	/**
	 * 获取用户头像，如无则返回“”
	 * 
	 * @return
	 */
	public String getPhone() {
		UserLoginVo vo = getLoginUser();
		if (vo != null && StringUtil.isNotBlank(vo.getPhone())) {
			return vo.getPhone();
		}
		return "";
	}

	/**
	 * 获取用户头像，如无则返回“”
	 * 
	 * @return
	 */
	public String getLogo() {
		UserLoginVo vo = getLoginUser();
		if (vo != null && StringUtil.isNotBlank(vo.getLogo())) {
			return vo.getLogo();
		}
		return "";
	}

	/**
	 * 获取用户昵称，如无则返回“”
	 * 
	 * @return
	 */
	public String getNick() {
		UserLoginVo vo = getLoginUser();
		if (vo != null && StringUtil.isNotBlank(vo.getNick())) {
			return vo.getNick();
		}
		return "";
	}

	/**
	 * 获取当前登陆信息-userId、头像、昵称、手机账号信息，如未登陆，则返回null
	 * 
	 * @return
	 */
	public UserLoginVo getLoginUser() {
		HttpServletRequest request = getRequest();
		if (request != null) {
			String loginToken = request.getHeader(UserConst.MAPKEY_USER_LOGIN_TOKEN);
			if (StringUtil.isNotBlank(loginToken)) {
				return userLoginService.getCacheByToken(loginToken);
			}
		}
		return null;
	}

	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		return request;
	}

	public HttpServletResponse getResponse() {
		HttpServletResponse response = ((ServletWebRequest) RequestContextHolder.getRequestAttributes()).getResponse();
		return response;
	}

//	@ExceptionHandler
//	public void exp(HttpServletRequest request, HttpServletResponse response, Exception ex) {
//		PrintWriter writer = null;
//		try {
//			String errStr = "系统繁忙，请稍后再试";
//			int code = RespEnum.EXCEPTION.getCode();
//			if (ex instanceof LoginException) {
//				code = RespEnum.LOGIN.getCode();
//				if (StringUtils.isNotBlank(ex.getMessage())) {
//					errStr = RespEnum.LOGIN.getDesc();
//				}
//			} else if (ex instanceof BizzException || ex instanceof PayException || ex instanceof OrderException) {
//				if (StringUtils.isNotBlank(ex.getMessage())) {
//					errStr = ex.getMessage();
//				}
//			} else if (ex.getMessage().indexOf(LoginException.class.getName()) >= 0) {
//				code = RespEnum.LOGIN.getCode();
//				errStr = CoreConst.VALUE_CORE_UNLOGIN_MSG;
//			}
//			Result retDomain = new Result();
//			retDomain.setCode(code);
//			retDomain.setMsg(errStr);
//			String json = JsonUtil.toJson(retDomain);
//			writer = response.getWriter();
//			// writer.write(json);
//			writer.flush();
//			writer.close();
//			log.error("系统异常,e={},{}", ex, ex.getStackTrace());
//			ex.printStackTrace();
//		} catch (Exception e) {
//			log.error("系统异常,e={},{}", e, e.getStackTrace());
//			e.printStackTrace();
//		} finally {
//			if (writer != null) {
//				writer.close();
//			}
//		}
//	}

	@ExceptionHandler
	@ResponseBody
	public String globleExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) {
		log.error("BaseWebController globleExceptionHandler Exception" + ex.getMessage(),ex);
		String errStr = "系统繁忙，请稍后再试";
		int code = RespEnum.EXCEPTION.getCode();
		if (ex instanceof LoginException) {
			code = RespEnum.LOGIN.getCode();
			if (StringUtils.isNotBlank(ex.getMessage())) {
				errStr = RespEnum.LOGIN.getDesc();
			}
		} else if (ex instanceof BizzException || ex instanceof PayException || ex instanceof OrderException) {
			if (StringUtils.isNotBlank(ex.getMessage())) {
				errStr = ex.getMessage();
			}
		} else if (ex.getMessage().indexOf(LoginException.class.getName()) >= 0) {
			code = RespEnum.LOGIN.getCode();
			errStr = CoreConst.VALUE_CORE_UNLOGIN_MSG;
		}
		Result retDomain = new Result();
		retDomain.setCode(code);
		retDomain.setMsg(errStr);
		String json = JsonUtil.toJson(retDomain);
		return json;
	}
}
